import 'package:flutter/material.dart';
import '../model/health_record.dart';
import '../service/database_service.dart';
import 'package:intl/intl.dart';

class RecordsList extends StatefulWidget {
  final RecordType? type;

  const RecordsList({Key? key, this.type}) : super(key: key);

  @override
  _RecordsListState createState() => _RecordsListState();
}

class _RecordsListState extends State<RecordsList> {
  final _scrollController = ScrollController();
  bool _isLoading = false;
  bool _hasMore = true;
  final List<HealthRecord> _records = [];
  static const int _pageSize = 20;

  @override
  void initState() {
    super.initState();
    _loadRecords();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  Future<void> _loadRecords() async {
    if (_isLoading || !_hasMore) return;

    setState(() {
      _isLoading = true;
    });

    try {
      final records = await DatabaseService().getHealthRecords(
        type: widget.type,);

      setState(() {
        _records.addAll(records);
        _hasMore = records.length == _pageSize;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('加载失败: $e')));
    }
  }

  void _onScroll() {
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent - 200) {
      _loadRecords();
    }
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: () async {
        _records.clear();
        _hasMore = true;
        await _loadRecords();
      },
      child:
          _records.isEmpty && !_isLoading
              ? Center(child: Text('暂无记录'))
              : ListView.separated(
                controller: _scrollController,
                itemCount: _records.length + (_hasMore ? 1 : 0),
                separatorBuilder: (context, index) => Divider(height: 1),
                itemBuilder: (context, index) {
                  if (index == _records.length) {
                    return Center(
                      child: Padding(
                        padding: EdgeInsets.all(16.0),
                        child: CircularProgressIndicator(),
                      ),
                    );
                  }

                  final record = _records[index];
                  return ListTile(
                    leading: _buildRecordIcon(record.type),
                    title: Text(_getRecordTitle(record)),
                    subtitle: Text(_formatRecordData(record)),
                    trailing: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Text(
                          DateFormat('MM-dd').format(record.timestamp),
                          style: TextStyle(color: Colors.grey),
                        ),
                        Text(
                          DateFormat('HH:mm').format(record.timestamp),
                          style: TextStyle(color: Colors.grey, fontSize: 12),
                        ),
                      ],
                    ),
                    onTap: () => _showRecordDetails(context, record),
                  );
                },
              ),
    );
  }

  Widget _buildRecordIcon(RecordType type) {
    IconData icon;
    Color color;
    debugPrint(type.name);
    switch (type) {
      case RecordType.feeding:
        icon = Icons.baby_changing_station;
        color = Colors.blue;
        break;
      case RecordType.diaper:
        icon = Icons.cleaning_services;
        color = Colors.green;
        break;
      case RecordType.sleep:
        icon = Icons.bedtime;
        color = Colors.purple;
        break;
      case RecordType.temperature:
        icon = Icons.thermostat;
        color = Colors.red;
        break;
      case RecordType.medicine:
        icon = Icons.medication;
        color = Colors.orange;
        break;
      case RecordType.vaccine:
        icon = Icons.vaccines;
        color = Colors.teal;
        break;
      default:
        icon = Icons.event_note;
        color = Colors.grey;
    }

    return Container(
      padding: EdgeInsets.all(8),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        shape: BoxShape.circle,
      ),
      child: Icon(icon, color: color),
    );
  }

  String _getRecordTitle(HealthRecord record) {
    switch (record.type) {
      case RecordType.feeding:
        return '喂奶';
      case RecordType.diaper:
        return '换尿布';
      case RecordType.sleep:
        return '睡眠';
      case RecordType.temperature:
        return '体温';
      case RecordType.medicine:
        return '用药';
      case RecordType.vaccine:
        return '疫苗';
      default:
        return '其他';
    }
  }

  String _formatRecordData(HealthRecord record) {
    switch (record.type) {
      case RecordType.feeding:
        return '${record.data['amount']}ml';
      case RecordType.diaper:
        return record.data['type'] == 'wet' ? '尿尿' : '便便';
      case RecordType.sleep:
        final duration = record.data['duration'] as int;
        final hours = duration ~/ 60;
        final minutes = duration % 60;
        return '${hours}小时${minutes}分钟';
      case RecordType.temperature:
        return '${record.data['temperature']}°C';
      case RecordType.medicine:
        return record.data['name'];
      case RecordType.vaccine:
        return record.data['name'];
      default:
        return record.data['notes'] ?? '';
    }
  }

  void _showRecordDetails(BuildContext context, HealthRecord record) {
    showModalBottomSheet(
      context: context,
      builder:
          (context) => Container(
            padding: EdgeInsets.all(16),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _getRecordTitle(record),
                  style: Theme.of(context).textTheme.titleLarge,
                ),
                SizedBox(height: 8),
                Text(
                  DateFormat('yyyy-MM-dd HH:mm').format(record.timestamp),
                  style: TextStyle(color: Colors.grey),
                ),
                SizedBox(height: 16),
                Text(_formatRecordData(record)),
                if (record.data['notes'] != null) ...[
                  SizedBox(height: 8),
                  Text(
                    '备注: ${record.data['notes']}',
                    style: TextStyle(color: Colors.grey),
                  ),
                ],
              ],
            ),
          ),
    );
  }
}
